#include "device/ec200/AtNetworkMqttRouteEC200.h"

AtNetworkMqttRouteEC200::AtNetworkMqttRouteEC200(AtNetworkMqttClient *client, AtNetworkDevice *device) {
  this->topicArr = (TOPIC_ITEM)MEM_ALLOC(TOPIC_LEN * MQTT_TOPIC_NUM_SIZE);
  this->urcCmd = (GSM_STRING)MEM_ALLOC(MQTT_TOPIC_URC_SIZE);
  this->topicNum = MQTT_TOPIC_NUM_SIZE;

  memset(this->topicArr, 0, TOPIC_LEN * MQTT_TOPIC_NUM_SIZE);
  memset(this->urcCmd, 0, MQTT_TOPIC_URC_SIZE);

  this->client = client;
  this->device = device;
}

AtNetworkMqttRouteEC200::~AtNetworkMqttRouteEC200() {
  free(this->topicArr);
  free(this->urcCmd);
}

/**
 * URC回调接口函数
 * +QMTRECV: <client_idx>,<msgid>,<topic>[,<payload_len>],<payload>
 */
void AtNetworkMqttRouteEC200::callback(void *param) {
  // 读取消息ID---------------------------------------------------------------
  int msgid = this->device->streamGetInt(8, ',');
  if (!this->device->streamSkipUntil('"')) {
    return;
  }

  // 读取消息主题-------------------------------------------------------------
  char *topic_body = (char *)MEM_ALLOC(128);
  this->device->streamGet(topic_body, 127, '"');
  if (!this->device->streamSkipUntil(',')) {
    free(topic_body);

    return;
  }

  // 读取消息内容长度---------------------------------------------------------
  int payload_len = this->device->streamGetInt(8, ',');
  if (!this->device->streamSkipUntil('"')) {
    free(topic_body);

    return;
  }

  // 读取消息内容-------------------------------------------------------------
  char *payload_body = (char *)MEM_ALLOC(payload_len + 1);
  this->device->streamGet(payload_body, payload_len);
  this->device->streamReleaseInvalidLegacyData();

  // 根据消息主题对消息进行路由------------------------------------------------
  for (size_t index = 0; index < this->topicNum; index++) {
    AtNetworkMqttTopic *item = this->topicArr[index];
    if (item != 0 && item->topic && item->callback) {
      if (strcmp(topic_body, item->topic) == 0) {
        item->callback(payload_len, payload_body);

        break;
      }
    }
  }

  // 释放资源----------------------------------------------------------------
  free(payload_body);
  free(topic_body);
}